package com.ynkbny.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ynkbny.base.PageResult;
import com.ynkbny.domain.Egconservation;
import com.ynkbny.domain.Enterprise;
import com.ynkbny.domain.pojo.EnterpriseGetNameVO;
import com.ynkbny.lgapi.YnBk;
import com.ynkbny.mapper.EgconservationMapper;
import com.ynkbny.mapper.EnterpriseMapper;
import com.ynkbny.service.EgconservationService;
import com.ynkbny.util.ConvertBeanUtil;
import com.ynkbny.util.DataPushUtil;
import com.ynkbny.util.SearchUtil;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 杨亚
 * @version 1.0.0
 * @title 针对表【t_ep_egconservation(用能单位节能项目情况信息 用能单位节能项目情况信息)】的数据库操作Service实现
 * @description 针对表【t_ep_egconservation(用能单位节能项目情况信息 用能单位节能项目情况信息)】的数据库操作Service实现
 * @create 2023-11-22 14:15:37
 **/
@Slf4j
@Service
public class EgconservationServiceImpl extends ServiceImpl<EgconservationMapper, Egconservation>
        implements EgconservationService {

    @Resource
    private YnBk ynBk;

    @Value("${laoGouWeb.getEgconservation}")
    private String getEgconservation;


    @Resource
    private DataPushUtil dataPushUtil;

    @Value("${measurement.pushCompanyEnergyConservation}")
    private  String pushUrl;

    @Resource
    private EnterpriseMapper enterpriseMapper;

    @Override
    public void getDataForLaoGou(String token, @NotNull EnterpriseGetNameVO enterpriseGetNameVO) {
        Integer proId = Integer.valueOf(enterpriseGetNameVO.getEnterpriseId());
        String enterpriseCode = enterpriseGetNameVO.getEnterpriseCode();
        JSONObject jsonObject = ynBk.getDataForLaoGou(getEgconservation, token, proId);
        if (jsonObject.getInteger("code") == 200) {
            List<Map<String, Object>> maps = (List<Map<String, Object>>) JSONArray.parse(jsonObject.getString("rows"));
            // 原数据map转bean 对应关系
            var list = ConvertBeanUtil.convertEgConservation(maps, enterpriseCode);
            list.forEach(n -> {
                n.setRegVersion("1.0版本");
                n.setDicVersion("1.0版本");
            });
            var lambdaQueryWrapper = new LambdaQueryWrapper<Egconservation>();
            lambdaQueryWrapper.eq(Egconservation::getEnterpriseCode, enterpriseCode);
            var oldList = this.list(lambdaQueryWrapper);

            var editList = new ArrayList<Egconservation>();

            var iterator = list.iterator();
            while (iterator.hasNext()) {
                var oldIterator = oldList.iterator();
                var temp = iterator.next();
                while (oldIterator.hasNext()) {
                    var old = oldIterator.next();
                    if (temp.getDataId().equals(old.getDataId())) {
                        editList.add(temp);
                        oldIterator.remove();
                        iterator.remove();
                        break;
                    }
                }
            }
            if (!list.isEmpty()) {
                this.saveBatch(list);
            }
            if (!editList.isEmpty()) {
                this.updateBatchById(editList);
            }
            if (!oldList.isEmpty()) {
                this.removeBatchByIds(oldList.stream().map(Egconservation::getDataId).collect(Collectors.toList()));
            }
        }
    }

    /**
     * 上传数据
     *
     * @param enterpriseCode 社会信用代码
     * @param token  AK
     */
    @Override
    public void pushData(String enterpriseCode, String token) {
        this.listByMap(new HashMap<String, Object>() {{
            put("enterprise_code", enterpriseCode);
        }}).forEach(object -> {
            try {
                this.updateById(this.entityClass.cast(dataPushUtil.pushData(token, object, pushUrl)));
            } catch (Exception e) {
                log.info("数据推送失败", e);
            }
        });
    }

    /**
     * 新增
     *
     * @param egconservation
     * @return
     */
    @Override
    public boolean add(Egconservation egconservation) {
        egconservation.setDicVersion("1.0版本");
        egconservation.setRegVersion("1.0版本");
        return this.save(egconservation);
    }

    /**
     * 删除
     *
     * @param egconservation
     * @return
     */
    @Override
    public boolean delete(Egconservation egconservation) {
        return this.removeById(egconservation);
    }

    /**
     * 修改
     *
     * @param egconservation
     * @return
     */
    @Override
    public boolean update(Egconservation egconservation) {
        return this.updateById(egconservation);
    }

    /**
     * 分页查询
     *
     * @param pageNum
     * @param pageSize
     * @param condition
     * @return
     */
    @Override
    public PageResult<Egconservation> pageList(Long pageNum, Long pageSize, String condition) {
        Page<Egconservation> page=new Page<>(pageNum,pageSize);
        String enterpriseCode=null;
        QueryWrapper<Egconservation> queryWrapper = null;
        Page<Egconservation> pageList = null;
        Enterprise enterprise=enterpriseMapper.selectById(condition);
        if (enterprise != null) {
            enterpriseCode = enterprise.getEnterpriseCode();
            queryWrapper = new QueryWrapper<Egconservation>().eq("enterprise_code", enterpriseCode);
            pageList = this.baseMapper.selectPage(page, queryWrapper);
            return new PageResult<>(pageList);
        }else {
            return null;
        }
    }

}




